package com.atguigu.gmall.item.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.item.service.ItemService;
import com.atguigu.gmall.list.client.ListFeignClient;
import com.atguigu.gmall.model.product.BaseCategoryView;
import com.atguigu.gmall.model.product.SkuInfo;
import com.atguigu.gmall.model.product.SpuSaleAttr;
import com.atguigu.gmall.product.client.ProductFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

@Service
public class ItemServiceImpl implements ItemService {

    @Autowired
    private ProductFeignClient productFeignClient;

    @Autowired
    private ThreadPoolExecutor threadPool;

    @Autowired
    private ListFeignClient listFeignClient;

    public Map getItem(Long skuId) {
        Map result = new HashMap();

        CompletableFuture<SkuInfo> skuInfoFuture = CompletableFuture.supplyAsync(() -> {
            //1.获取sku的基本信息
            SkuInfo skuInfo = productFeignClient.getSkuInfo(skuId);
            result.put("skuInfo",skuInfo);
            return skuInfo;
        },threadPool);
        CompletableFuture<BaseCategoryView> categoryViewFuture = skuInfoFuture.thenApplyAsync((skuInfo) -> {
            //2.三级分类列表
            BaseCategoryView baseCategoryView = productFeignClient.getBaseCategoryView(skuInfo.getCategory3Id());
            result.put("categoryView", baseCategoryView);
            return baseCategoryView;
        });
        CompletableFuture<List<SpuSaleAttr>> spuSaleAttrListFuture = skuInfoFuture.thenApplyAsync((skuInfo) -> {
            //3.获取所有的属性与属性值
            List<SpuSaleAttr> spuSaleAttrAndValue = productFeignClient.getSpuSaleAttrAndValue(skuInfo.getSpuId(), skuId);
            result.put("spuSaleAttrList", spuSaleAttrAndValue);
            return spuSaleAttrAndValue;
        });
        CompletableFuture<String> valuesSkuJsonFutrue = skuInfoFuture.thenApplyAsync((skuInfo) -> {
            //4.根据销售属性组合的变化改变skuId
            Map skuValueIdsMap = productFeignClient.getSkuValueIdsMap(skuInfo.getSpuId());
            String skuValueIdsString = JSONObject.toJSONString(skuValueIdsMap);
            result.put("valuesSkuJson", skuValueIdsString);
            return skuValueIdsString;
        });
        //5.获取价格
        BigDecimal price = productFeignClient.getPrice(skuId);

        //6.增加商品热度
        listFeignClient.addHotScore(skuId);
        result.put("price",price);

        CompletableFuture.allOf(skuInfoFuture,categoryViewFuture,spuSaleAttrListFuture,valuesSkuJsonFutrue).join();


        return result;
    }
}
